package com.mrd.gtimpframe.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.mrd.gtimpframe.entity.TSysJob;
import com.mrd.gtimpframe.service.TSysJobService;

/**
 * 初始化调度器，先手动初始化，添加要执行的定时器，后面改造成读取数据库
 * 
 * @author han
 */
@Component
public class TaskInitBean implements InitializingBean {

  @Autowired
  SchedulerFactoryBean schedulerFactoryBean;
  @Autowired
  private TSysJobService tSysJobService;

  /**
   * spring 初始化方法，把要调度的定时器在这里初始化
   * 
   * @auhtor han
   */
  @Override
  public void afterPropertiesSet() throws Exception {
    // List<TSysJob> list = tSysJobService.queryList(new TSysJob());
    // if (list != null && list.size() > 0) {
    //
    // Scheduler scheduler = schedulerFactoryBean.getScheduler();
    // List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
    // for (TSysJob sysJob : list) {
    // if (StringUtils.isNotEmpty(sysJob.getJobStatus()) && sysJob.getJobStatus().equals("1"))
    // addJob(sysJob);
    // }
    // }
  }

  /**
   * 添加任务
   * 
   * @author han
   * @param scheduleJob
   * @throws SchedulerException
   */
  public void addJob(TSysJob job) throws Exception {
    if (job == null || !TSysJob.STATUS_RUNNING.equals(job.getJobStatus())) {
      return;
    }

    Scheduler scheduler = schedulerFactoryBean.getScheduler();
    TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
    Class clazz = (Class.forName(job.getBeanClass()).newInstance()).getClass();
    JobDetail jobDetail =
        JobBuilder.newJob(clazz).withIdentity(job.getJobName(), job.getJobGroup()).build();
    jobDetail.getJobDataMap().put("scheduleJob", job);
    CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
    trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup())
        .withSchedule(scheduleBuilder).build();
    scheduler.scheduleJob(jobDetail, trigger);
  }

}
